#include "qpenciltool.h"
#include <QGraphicsSceneMouseEvent>
#include <QGraphicsSceneContextMenuEvent>

QPencilTool::QPencilTool(QObject *parent)
	: QMyTool(parent),isDrawing(false),temp(0),path(),last(),record()
{

}

QPencilTool::~QPencilTool()
{

}

void QPencilTool::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * mouseEvent)
{
}
void QPencilTool::mouseMoveEvent(QGraphicsSceneMouseEvent * mouseEvent)
{
	if(isDrawing)
	{
		QPointF now=mouseEvent->scenePos();
		QPointF dis=now-last;
		qreal x=dis.x();
		qreal y=dis.y();
		if(sqrt(x*x+y*y)>3)
		{
			path.lineTo(now);
			temp->setPath(path);
			last=now;
			record.append(last);
		}
	}
}
void QPencilTool::mousePressEvent(QGraphicsSceneMouseEvent * mouseEvent)
{
	isDrawing=true;
	last=mouseEvent->scenePos();
	path.moveTo(last);
	temp=new QGraphicsPathItem(0,Container);
	temp->setPen(Container->Pen());
	temp->setBrush(Container->Brush());
	record.append(last);
}
void QPencilTool::mouseReleaseEvent(QGraphicsSceneMouseEvent * mouseEvent)
{
	isDrawing=false;
	controller->receiveMessage(new NewNodeMessage(NewNodeArgs(pathNode,QPointF(),record)));
	record.clear();
	path=QPainterPath();
	int i=controller->NumberOfObjects()-1;
	if(controller->GetNodeType(-1)==MovieClip)
	{
		Container->removeItem(temp);
		delete temp;
		temp=0;
		
		controller->receiveMessage(new SelectContainerMessage(i));
		i=controller->NumberOfObjects()-1;
		((ShapeNode*)(controller->GetObjectByIndex(i)))->LinePenRef()=Container->Pen();
		((ShapeNode*)(controller->GetObjectByIndex(i)))->FillBrushRef()=Container->Brush();
			((ShapeNode*)(controller->GetObjectByIndex(-1)))->SetDirty();
		((ShapeNode*)(controller->GetObjectByIndex(-1)))->UpdateCache();
		controller->receiveMessage(new SelectContainerMessage());
			i=controller->NumberOfObjects()-1;
			Container->AddPixmapItem(i);
	}
	else
	{
		Container->AddItemLink(temp,i);
		temp->setFlag(QGraphicsItem::ItemIsSelectable, true);
		temp->setFlag(QGraphicsItem::ItemSendsGeometryChanges, true);
		((ShapeNode*)(controller->GetObjectByIndex(i)))->LinePenRef()=Container->Pen();
		((ShapeNode*)(controller->GetObjectByIndex(i)))->FillBrushRef()=Container->Brush();
			((ShapeNode*)(controller->GetObjectByIndex(-1)))->SetDirty();
		((ShapeNode*)(controller->GetObjectByIndex(-1)))->UpdateCache();
	}
}
void QPencilTool::contextMenuEvent(QGraphicsSceneContextMenuEvent * mouseEvent)
{

}